package net.jueb.majong.voice.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.jueb.majong.voice.util.Config;

public class WebFilter implements Filter{

	protected Logger log=LoggerFactory.getLogger(getClass());
	@Override
	public void destroy() {
		
	}
	
	protected void printHeaders(HttpServletRequest request)
	{
		String uri=request.getRequestURI();
		String servletPath=request.getServletPath();
		String pathInfo=request.getPathInfo();
		StringBuffer sb=new StringBuffer();
		sb.append("\n");
		sb.append("**********uri:"+uri+"**********\n");
		sb.append("servletPath:"+servletPath+",pathInfo:"+pathInfo+"\n");
		sb.append("args:\n");
		for(Entry<String, String[]> entry:request.getParameterMap().entrySet())
		{
			sb.append(entry.getKey()+"="+Arrays.toString(entry.getValue())+"\n");
		}
		sb.append("headers:\n");
		Enumeration<String> names=request.getHeaderNames();
		while(names.hasMoreElements())
		{
			String name=names.nextElement();
			String value=request.getHeader(name);
			sb.append(name+":"+value+"\n");
		}
		sb.append("**********end**********\n");
		log.debug(sb.toString());
	}
	
	/**
	 * 跨域配置
	 */
	protected void initCros(HttpServletRequest request,HttpServletResponse response)
	{
		String origin=request.getHeader("Origin");//请求来源地址
		if(origin!=null)
		{//不是本地前端请求(跨域前端请求)
			if(Config.ACCESS_ORIGIN_LIST.contains("*") ||Config.ACCESS_ORIGIN_LIST.contains(origin))
			{//测试模式-直接允许任意请求来源 或者 正式模式跨域白名单包含此来源
				//允许跨域的请求来源站点,如果Credentials=true,则不能使用*
				response.setHeader("Access-Control-Allow-Origin",origin);
				//附带凭证信息的请求
				response.setHeader("Access-Control-Allow-Credentials", "true");
				//允许跨域请求的方式
				response.setHeader("Access-Control-Allow-Methods", "POST,GET");
				//允许自定义的头部,以逗号隔开,大小写不敏感
				String requestHeaders=request.getHeader("access-control-request-headers");
				response.setHeader("Access-Control-Allow-Headers",requestHeaders);
				//设置浏览器允许访问的服务器的头信息的白名单
				response.setHeader("Access-Control-Expose-Headers","Set-Cookie");
			}
		}
	}
	
	@Override
	public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain)throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) req;
		HttpServletResponse response=(HttpServletResponse) rsp;
		printHeaders(request);
		initCros(request, response);
		chain.doFilter(req, rsp);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
}
